<script setup lang="ts">
	defineOptions({
		name: 'Login',
	})

	import { useAppStore } from '@/store'
	import { login, getCodeImg } from '@/api/app'
	import { generateDynamicRoutes } from '@/router'

	import type { LoginData, LoginResult } from '@/api/app/types'
	type FormInstance = InstanceType<typeof ElForm>

	const router = useRouter()
	const appStore = useAppStore()
	const loginFormRef = ref<FormInstance>()
	const loading = ref(false)
	const captchaEnabled = ref<boolean>(true)
	const codeUrl = ref('')
	const loginForm = reactive<LoginData>({ username: 'admin', password: 'admin123', code: '', uuid: '' })
	const loginRules = reactive({
		username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
		password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
		code: [{ required: true, message: '请输入验证码', trigger: 'change' }],
	})

	const resetForm = () => {
		loginFormRef.value?.resetFields()
	}

	const getCode = () => {
		getCodeImg().then((res) => {
			console.log('res---', res)
			const { enabled, uuid, img } = res.data
			captchaEnabled.value = enabled ?? true
			if (captchaEnabled.value) {
				codeUrl.value = img
				loginForm.uuid = uuid
			}
		})
	}

	const handleLogin = () => {
		loginFormRef.value?.validate(async (valid) => {
			if (!valid) return
			loading.value = true
			try {
				const { data } = await login<LoginResult, LoginData>({ ...loginForm })
				appStore.setToken(data.accessToken)
				console.log('login res：', data)
				await generateDynamicRoutes()

				console.log('router：', router.getRoutes())
				router.push('/')
			} finally {
				loading.value = false
			}
		})
	}

	onMounted(() => {
		document.onkeydown = (e: KeyboardEvent) => {
			if (e.code === 'Enter' || e.code === 'NumpadEnter') {
				if (loading.value) return
				handleLogin()
			}
		}
		getCode()
	})
	onBeforeUnmount(() => {
		document.onkeydown = null
	})
</script>

<template>
	<div class="login-container">
		<el-card class="login-card">
			<div class="flex pb-20 flex-justify-center flex-items-center font-size-32">
				<img src="/vite.svg" class="w-xs" alt="Vite logo" />
				<span class="pl-10 font-bold">后台管理系统模板</span>
			</div>
			<el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
				<el-form-item prop="username">
					<el-input v-model="loginForm.username" placeholder="用户名：admin / user" cleard>
						<template #prefix>
							<i class="i-ep-user font-size-18"></i>
						</template>
					</el-input>
				</el-form-item>
				<el-form-item prop="password">
					<el-input v-model="loginForm.password" type="password" placeholder="密码：123456" auto-complete="off" show-password cleard>
						<template #prefix>
							<i class="i-ep-lock font-size-18"></i>
						</template>
					</el-input>
				</el-form-item>
				<el-form-item v-if="captchaEnabled" prop="code">
					<div style="width: 100%; clear: both">
						<el-input v-model="loginForm.code" placeholder="验证码" auto-complete="off" style="width: 60%">
							<template #prefix>
								<i class="i-ct-valid-code font-size-18"></i>
							</template>
						</el-input>
						<div class="login-code" @click="getCode" v-html="codeUrl"></div>
						<!-- <img :src="codeUrl" alt="" class="login-code-img" @click="getCode" /> -->
					</div>
				</el-form-item>
			</el-form>

			<div class="login-btns">
				<el-button class="w-186" round size="large" type="primary" :loading="loading" @click="handleLogin"> 登录 </el-button>
				<el-button class="w-186" round size="large" @click="resetForm">重置</el-button>
			</div>
		</el-card>
	</div>
</template>

<style scoped>
	.login-container {
		width: 100%;
		height: 100%;
		margin: 0 auto;
		background: url('@/assets/img/login_bg.png') no-repeat center;
		background-size: cover;
		position: relative;
		.login-card {
			width: 400px;
			padding: 20px 30px 30px 30px;
			position: absolute;
			top: 50%;
			right: 8%;
			transform: translateY(-50%);
			.el-form-item {
				margin-bottom: 40px;
			}
			.login-code {
				width: 33%;
				height: 40px;
				float: right;
				.login-code-img {
					height: 40px;
					cursor: pointer;
					vertical-align: middle;
				}
			}
			.login-btns {
				display: flex;
				justify-content: space-between;
				width: 100%;
				margin-top: 38px;
				white-space: nowrap;
			}
		}
	}
</style>
